<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CreateLabel from "./components/CreateLabeling.vue";
import CompleteHandle from "./components/CompleteHandle.vue";
import AddPlannedTime from "./components/AddPlannedTime.vue";
import { getCargoPage, checkinTaskInProgress } from "/@/api/task";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { exportExcel } from "/@/utils/index";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
dayjs.extend(timezone);

defineOptions({
  name: "TransferTaskIndex"
});

// const router = useRouter();
const tableData = ref([]);
const query = reactive({
  // user_name: "",
  // planning_time: "",
  // status: null,
  is_ex_warehouse: 0,
  type: 2,
  currentPage: 1,
  pageSize: 15
});
const total = ref(0);
const createLabelingDia = ref(false);
const completeDia = ref(false);
const planDia = ref(false);
const planFormData = ref({
  id: "",
  planning_time: null
});
const completeFormData = ref({});

// 选中的list
let checkList = ref([]);

const handleSelectionChange = val => {
  checkList.value = val;
};

const exportTask = () => {
  const titleArr = [
    "客户名称",
    "类型",
    "出库方式",
    "去向",
    "箱麦",
    "数量",
    "总体积",
    "重量",
    "箱长",
    "箱宽",
    "箱高",
    "收货地址",
    "FBI ID",
    "Ref ID",
    "备注"
  ]; //表头中文名
  let data;
  if (!checkList.value.length) {
    if (!tableData.value.length) {
      ElMessage({
        type: "warning",
        message: "没有可导出数据请创建"
      });
    } else {
      data = tableData.value.map(item => {
        const {
          user_name,
          checkout_name,
          place_to_go,
          box_no,
          quantity,
          total_volume,
          weight,
          length,
          width,
          height,
          ship_to_address,
          fba_id,
          ref_id,
          notes
        } = item;
        const obj = {
          user_name,
          type: "中转",
          checkout_name,
          place_to_go,
          box_no,
          quantity,
          total_volume,
          weight,
          length,
          width,
          height,
          ship_to_address,
          fba_id,
          ref_id,
          notes
        };
        return obj;
      });
    }
  } else {
    data = checkList.value.map(item => {
      const {
        user_name,
        checkout_name,
        place_to_go,
        box_no,
        quantity,
        total_volume,
        weight,
        length,
        width,
        height,
        ship_to_address,
        fba_id,
        ref_id,
        notes
      } = item;
      const obj = {
        user_name,
        type: "中转",
        checkout_name,
        place_to_go,
        box_no,
        quantity,
        total_volume,
        weight,
        length,
        width,
        height,
        ship_to_address,
        fba_id,
        ref_id,
        notes
      };
      return obj;
    });
  }
  exportExcel(data, "中转", titleArr, "sheetName");
};

onMounted(() => {
  getTableData();
});

// const haveHandle = () => {
//   if (!checkList.value.length) {
//     return ElMessage({
//       message: "请勾选任务",
//       type: "warning"
//     });
//   } else {
//     ElMessageBox.confirm("是否把状态置为进行中?", "提示", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning"
//     })
//       .then(() => {
//         const multi_id = checkList.value.map(item => item.id);
//         checkinTaskInProgress({ multi_id }).then(() => {
//           ElMessage({
//             type: "success",
//             message: "操作成功"
//           });
//           getTableData();
//         });
//       })
//       .catch(() => {});
//   }
// };

const getTableData = () => {
  getCargoPage(query).then((res: any) => {
    if (Object.prototype.toString.call(res.data.data) === "[object Object]") {
      tableData.value = [];
    } else {
      tableData.value = res.data.data;
    }
    total.value = res.data.total;
  });
};

const handleSizeChange = val => {
  query.pageSize = val;
  getTableData();
};

const handleCurrentChange = val => {
  query.currentPage = val;
  getTableData();
};

const submitSuccess = () => {
  getTableData();
};

// const filterStatus = val => {
//   if (val === "1") {
//     return "未完成";
//   } else if (val === "2") {
//     return "进行中";
//   } else {
//     return "已完成";
//   }
// };

// const filterType = val => {
//   if (val === "1") {
//     return "提柜";
//   } else if (val === "2") {
//     return "中转";
//   } else {
//     return "退件";
//   }
// };

// const addPlanned = ({ id, planning_time }) => {
//   planFormData.value = {
//     id,
//     planning_time: planning_time
//       ? dayjs(planning_time * 1000).format("YYYY-MM-DD HH:mm:ss")
//       : ""
//   };
//   planDia.value = true;
// };

// const complete = row => {
//   const obj = { ...row };
//   obj.completion_time = obj.completion_time
//     ? dayjs(obj.completion_time * 1000).format("YYYY-MM-DD HH:mm:ss")
//     : "";
//   obj.bill_name = getBillName();
//   obj.bill_description = "";
//   obj.bill_rate = 0;
//   completeFormData.value = obj;
//   completeDia.value = true;
// };

// const getBillName = () => {
//   const path = router.currentRoute.value.path;
//   if (path === "/task/labeling") {
//     return "贴标";
//   } else if (path === "/task/transfer") {
//     return "中转";
//   } else if (path === "/task/liftingCabinet") {
//     return "提柜";
//   } else if (path === "/task/distribution") {
//     return "一件代发";
//   } else if (path === "/task/return") {
//     return "退货";
//   } else {
//     return "";
//   }
// };
</script>

<template>
  <div class="transfer-task-warp">
    <el-card>
      <!-- search start -->
      <!-- <el-form :inline="true" :model="query" label-width="auto">
        <el-form-item label="客户名称:">
          <el-input v-model="query.user_name" />
        </el-form-item>
        <el-form-item
          label="规划时间:"
          v-auth="['admin', 'super', 'warehouse']"
        >
          <el-date-picker
            v-model="query.planning_time"
            type="date"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="query.status" clearable>
            <el-option label="未完成" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="getTableData">搜 索</el-button>
        </el-form-item>
      </el-form> -->
      <!-- search end -->

      <!-- btns start -->
      <!-- <div>
        <el-button
          type="primary"
          @click="exportTask"
          v-auth="['admin', 'super', 'warehouse']"
          >导出任务</el-button
        >
        <el-button
          type="primary"
          @click="haveHandle"
          v-auth="['admin', 'super', 'warehouse']"
          >进行中按钮</el-button
        >
      </div> -->
      <!-- btns end -->

      <!-- tabel start -->
      <el-table
        ref="multipleTableRef"
        border
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div style="padding-left: 20px">
              <el-table :data="row.subtasks" size="small">
                <el-table-column prop="place_to_go" label="去向" />
                <el-table-column prop="box_no" label="箱麦" />
                <el-table-column prop="" label="柜号" />
                <el-table-column label="出库方式">
                  <template #default>
                    <div>中转</div>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="客户名称" />
                <el-table-column prop="" label="类型" />
                <el-table-column prop="quantity" label="数量" />
                <el-table-column prop="total_volume" label="总体积" />
                <el-table-column prop="weight" label="重量" />
                <el-table-column prop="length" label="箱长" />
                <el-table-column prop="width" label="箱宽" />
                <el-table-column prop="height" label="箱高" />
                <el-table-column prop="ship_to_address" label="收货地址" />
                <el-table-column prop="fba_id" label="FBA ID" />
                <el-table-column prop="ref_id" label="Fef ID" />
                <el-table-column prop="fee" label="费用" />
                <el-table-column prop="is_temporary_storage" label="是否暂扣" />
                <el-table-column prop="notes" label="备注" />
                <el-table-column prop="completion_time" label="完成时间" />
                <el-table-column label="创建时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.created_at
                        ? dayjs(row.created_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="更新时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.updated_at
                        ? dayjs(row.updated_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button size="small" type="primary">暂扣</el-button>
                    <el-button size="small" type="primary">修改</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="identifier" label="编号" />
        <el-table-column prop="user_name" label="客户名称" />
        <el-table-column prop="container_no" label="柜号" />
        <el-table-column prop="bill_of_lading" label="提单号" />
        <el-table-column prop="shipping_company" label="船司" />
        <el-table-column prop="notes" label="备注" />
        <el-table-column prop="estimated_time" label="预计到柜时间" />
        <!-- <el-table-column label="类型">
          <template #default="{ row }">
            {{ filterType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkout_name" label="出库方式" />
        <el-table-column prop="place_to_go" label="去向" />
        <el-table-column prop="box_no" label="箱麦" />
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="total_volume" label="总体积" />
        <el-table-column prop="weight" label="重量" />
        <el-table-column prop="length" label="箱长" />
        <el-table-column prop="width" label="箱宽" />
        <el-table-column prop="height" label="箱高" />
        <el-table-column prop="ship_to_address" label="收货地址" />
        <el-table-column prop="fba_id" label="FBA ID" />
        <el-table-column prop="ref_id" label="Ref ID" /> -->
        <!-- <el-table-column label="状态">
          <template #default="{ row }">
            {{ filterStatus(row.status) }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="规划时间" width="120">
          <template #default="{ row }">
            {{
              row.planning_time
                ? dayjs(row.planning_time * 1000).format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="完成时间" width="120">
          <template #default="{ row }">
            {{
              row.completion_time
                ? dayjs(row.completion_time * 1000).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                : ""
            }}
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.created_at
                ? dayjs(row.created_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.updated_at
                ? dayjs(row.updated_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="210"
          v-auth="['admin', 'super', 'warehouse']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small">出库</el-button>
            <el-button type="primary" size="small">修改</el-button>
            <el-button type="primary" size="small">添加去向</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- tabel end -->

      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 10, 15, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建贴标任务dialog start -->
    <create-label v-model="createLabelingDia" @submit-success="submitSuccess" />
    <!-- 创建贴标任务dialog start -->

    <!-- 添加规划时间dialog start -->
    <add-planned-time
      v-model="planDia"
      :plan-form-data="planFormData"
      @submit-success="submitSuccess"
    />
    <!-- 添加规划时间dialog end -->

    <!-- 完成按钮dialog start -->
    <complete-handle
      v-model="completeDia"
      :complete-form-data="completeFormData"
      @submit-success="submitSuccess"
    />
    <!-- 完成按钮dialog end -->
  </div>
</template>
